// pages/yourPage/yourPage.js
const url = getApp().globalData.API_URL;
const Uid = getApp().globalData.uid;
const app = getApp();
// const Uid = wx.getStorage("token");
const imageCdn = 'https://tdesign.gtimg.com/mobile/demos';
Page({
    data: {
        showTimeAndSelect: false,
        timetype: 1, // 默认时间类型为周
        zhichushourutype: 1, // 默认支出收入类型为支出
        weekvalue: '', // 周选择器的值
        yearMonthWeek: '', // 用于显示周/月/年的选择
        year: '', // 年份
        month: '', // 月份
        day: '', //日期
        Uid: '',
        dayList: [], //存放这周日期信息
        dayXList: [], //存放简易信息
        startDate: '', // 开始日期
        endDate: '', // 结束日期
        totalzhichu: 1, // 总支出
        totalshouru: 0, // 总收入
        chartData: {
            categories: [],
            series: [{
                name: '支出数据',
                data: []
            }]
        }, // 线性图数据
        ringChartData: {
            series: [{
                data: [

                ]
            }]
        }, // 环形图数据

        opts: {
            color: ["#1890FF"],
            padding: [15, 15, 0, 15],
            legend: {},
            duration: 500,
            enableScroll: true,
            xAxis: {
                disableGrid: true,
                scrollShow: true,
                itemCount: 10
            },
            yAxis: {
                gridType: "dash",
                dashLength: 2
            },
            extra: {
                area: {
                    type: "curve",
                    opacity: 0.1,
                    addLine: true,
                    width: 2,
                    gradient: true
                }
            }
        }, // 线性图选项
        ringOpts: {
            title: "收支数据",
            subtitle: "",
            padding: [5, 5, 5, 5],
            legend: {
                show: true,
                position: "right",
                lineHeight: 15
            },
            extra: {
                ring: {
                    ringWidth: 20,
                    activeOpacity: 0.5,
                    activeRadius: 10,
                    offsetAngle: 0,
                    labelWidth: 1,
                    border: true,
                    borderWidth: 1,
                    borderColor: "#FFFFFF"
                }
            }
        } // 环形图选项
    },

    onLoad() {
        // 页面初始化时加载数据
        this.loadInitialData();

    },
    onShow() {
        this.loadStatistics();
    },

    loadInitialData() {
        // 获取当天日期信息
        this.getCurrentDate();
        this.getdayXList();
        this.getWeekChartData();

        // 实现初始化数据加载逻辑
        this.getWeekChartData();
        this.loadStatistics();

    },
    getdayXList() {
        this.data.dayXList = this.data.dayList.map(dateStr => dateStr.slice(-2));
    },
    // 周表数据
    getWeekChartData() {
        wx.request({
            url: `${url}/getWeekChartData`, // 替换为你的后端API路径
            method: 'POST',
            data: {
                uid: Uid,
                dayList: this.data.dayList,
                zhichushourutype: this.data.zhichushourutype
            },
            success: (res) => {
                if (res.statusCode === 200) {
                    // 处理响应数据
                    console.log('Received data:', res.data);
                    this.setData({
                        totalshouru: res.data.totalshouru,
                        totalzhichu: res.data.totalzhichu
                    })
                    if (this.data.zhichushourutype == 1) {
                        this.setData({
                            chartData: {
                                categories: this.data.dayXList,
                                series: [{
                                    name: '支出数据',
                                    data: res.data.chartData
                                }]
                            }, // 线性图数据
                            ringChartData: {
                                series: [{
                                    data: res.data.ringData
                                }]
                            }, // 环形图数据
                        });
                    } else {
                        this.setData({
                            chartData: {
                                categories: this.data.dayXList,
                                series: [{
                                    name: '收入数据',
                                    data: res.data.chartData
                                }]
                            }, // 线性图数据
                            ringChartData: {
                                series: [{
                                    data: res.data.ringData
                                }]
                            }, // 环形图数据
                        });
                    }
                    this.setData({

                    });
                } else {
                    console.error('请求失败，状态码:', res.statusCode);
                }
            },
            fail: (error) => {
                console.error('请求失败:', error);
            }
        });
    },
    // 月表数据
    getMonthChartData() {
        wx.request({
            url: `${url}/getMonthChartData`, // 替换为你的后端API路径
            method: 'POST',
            data: {
                uid: Uid,
                yearmonth: this.data.year + this.data.month,
                zhichushourutype: this.data.zhichushourutype
            },
            success: (res) => {
                if (res.statusCode === 200) {
                    // 处理响应数据
                    console.log('Received data:', res.data);
                    this.setData({
                        totalshouru: res.data.totalshouru,
                        totalzhichu: res.data.totalzhichu
                    })
                    if (this.data.zhichushourutype == 1) {
                        this.setData({

                            chartData: {
                                categories: res.data.days,
                                series: [{
                                    name: '支出数据',
                                    data: res.data.chartData
                                }]
                            }, // 线性图数据
                            ringChartData: {
                                series: [{
                                    data: res.data.ringData
                                }]
                            }, // 环形图数据
                        });
                    } else {
                        this.setData({
                            chartData: {
                                categories: res.data.days,
                                series: [{
                                    name: '收入数据',
                                    data: res.data.chartData
                                }]
                            }, // 线性图数据
                            ringChartData: {
                                series: [{
                                    data: res.data.ringData
                                }]
                            }, // 环形图数据
                        });
                    }
                    this.setData({

                    });
                } else {
                    console.error('请求失败，状态码:', res.statusCode);
                }
            },
            fail: (error) => {
                console.error('请求失败:', error);
            }
        });
    },
    // 年表数据
    getYearChartData() {
        wx.request({
            url: `${url}/getYearChartData`, // 替换为你的后端API路径
            method: 'POST',
            data: {
                uid: Uid,
                yearmonth: this.data.year,
                zhichushourutype: this.data.zhichushourutype
            },
            success: (res) => {
                if (res.statusCode === 200) {
                    // 处理响应数据
                    console.log('Received data:', res.data);
                    this.setData({
                        totalshouru: res.data.totalshouru,
                        totalzhichu: res.data.totalzhichu
                    })
                    if (this.data.zhichushourutype == 1) {
                        this.setData({

                            chartData: {
                                categories: res.data.months,
                                series: [{
                                    name: '支出数据',
                                    data: res.data.chartData
                                }]
                            }, // 线性图数据
                            ringChartData: {
                                series: [{
                                    data: res.data.ringData
                                }]
                            }, // 环形图数据
                        });
                    } else {
                        this.setData({
                            chartData: {
                                categories: res.data.months,
                                series: [{
                                    name: '收入数据',
                                    data: res.data.chartData
                                }]
                            }, // 线性图数据
                            ringChartData: {
                                series: [{
                                    data: res.data.ringData
                                }]
                            }, // 环形图数据
                        });
                    }

                } else {
                    console.error('请求失败，状态码:', res.statusCode);
                }
            },
            fail: (error) => {
                console.error('请求失败:', error);
            }
        });
    },

    openZhangbenChoose() {
        // 打开账本选择
        this.selectComponent('#actionSheet').open();
    },
    // 收入支出模式转换
    changeShouruZhichuTab(event) {
        const zhichushourutype = parseInt(event.currentTarget.dataset.type, 10);

        // 设置数据
        this.setData({
            zhichushourutype: zhichushourutype
        }, () => {
            this.loadStatistics();
        });
    },
    // 获取本月第几周
    getWeekOfMonth(date) {
        const month = date.getMonth();
        const day = date.getDate();
        const startOfMonth = new Date(date.getFullYear(), month, 1);
        const startDayOfWeek = startOfMonth.getDay();
        const weekNumber = Math.ceil((day + startDayOfWeek) / 7);
        return weekNumber;
    },
    // 获取每周一的日期
    getWeekStartDate(date) {
        const dayOfWeek = date.getDay(); // 星期（0 = Sunday, 1 = Monday, ..., 6 = Saturday）
        const diffToMonday = dayOfWeek === 0 ? -6 : 1 - dayOfWeek;
        const weekStartDate = new Date(date.getTime() + diffToMonday * 24 * 60 * 60 * 1000);
        return weekStartDate;
    },

    // 获取每周日的日期
    getWeekEndDate(date) {
        const weekStartDate = this.getWeekStartDate(date);
        const weekEndDate = new Date(weekStartDate);
        weekEndDate.setDate(weekStartDate.getDate() + 6);
        return weekEndDate;
    },

    // 补零函数，确保月份是两位数
    padZero(num) {
        return num < 10 ? `0${num}` : num;
    },

    // 获取目前时间
    getCurrentDate() {
        const now = new Date();
        const year = now.getFullYear(); // 获取当前年份
        const month = String(now.getMonth() + 1).padStart(2, '0'); // 获取当前月份，并格式化为两位数

        // 计算当前日期在本月中的第几周
        const dayOfMonth = now.getDate(); // 获取当前日期的天数
        console.log("当前天数" + dayOfMonth);
        const currentWeekNumber = Math.ceil(dayOfMonth / 7); // 计算周数

        // 格式化为“YYYY年MM月第X周”
        const yearMonthWeek = `${year}年${month}月第${currentWeekNumber}周`;

        // 计算当前周的所有日期的 YYYYMMDD 格式
        // 计算当前周的开始日期
        const startDayOfMonth = (currentWeekNumber - 1) * 7 + 1;
        const startDateOfWeek = new Date(year, now.getMonth(), startDayOfMonth);

        const endDateOfWeek = new Date(startDateOfWeek);
        endDateOfWeek.setDate(startDateOfWeek.getDate() + 6); // 当前周的结束日期

        const dayList = [];
        for (let d = new Date(startDateOfWeek); d <= endDateOfWeek; d.setDate(d.getDate() + 1)) {
            const year = d.getFullYear();
            const month = String(d.getMonth() + 1).padStart(2, '0');
            const date = String(d.getDate()).padStart(2, '0');
            const formattedDate = `${year}${month}${date}`;
            dayList.push(formattedDate);
        }

        console.log(dayList);
        this.setData({
            year: year,
            month: month,
            weekvalue: currentWeekNumber,
            yearMonthWeek: yearMonthWeek,
            dayList: dayList, // 更新 dayList

        }, () => {
            // 这个回调函数会在数据更新完成后调用
            console.log(this.data.dayList, this.data.year, this.data.month, this.data.weekvalue, this.data.yearMonthWeek);
            this.getdayXList();
            // this.setData({
            //     chartData: {
            //         categories: this.data.dayXList,
            //         series: [
            //             {
            //                 name: '支出数据',
            //                 data: []
            //             }
            //         ]
            //     }, // 线性图数据
            // })

        });
        // console.log(this.dayList,this.year,this.month,this.weekvalue,this.yearMonthWeek);
    },
    // 改变周月年时间类型
    changeTimeType: function (event) {
        // 获取 data-type 的值
        const typeValue = parseInt(event.currentTarget.dataset.type, 10);
        // 设置数据
        this.setData({
            timetype: typeValue
        }, () => {
            // 此处应更新图表数据
            this.loadStatistics();
        });


    },
    openWeek(e) {
        // 目前时间
        const now = new Date();

        // 处理周选择器
        const selectedDate = new Date(e.detail.value);
        if (selectedDate > now) {
            wx.showToast({
                title: '选择的日期大于当前日期!',
                icon: 'none'
            });
        } else {
            const year = selectedDate.getFullYear();
            const month = selectedDate.getMonth() + 1; // 月份从0开始，所以需要加1
            // 计算周数
            const dayOfMonth = selectedDate.getDate();
            const weekNumber = Math.ceil(dayOfMonth / 7); // 每7天为一周

            // 格式化为“YYYY年MM月第X周”
            const yearMonthWeek = `${year}年${this.padZero(month)}月第${weekNumber}周`;

            const weekStartDate = this.getWeekStartDate(selectedDate); // 获取每周一
            const weekEndDate = this.getWeekEndDate(selectedDate); // 获取每周日

            // 获取周内所有日期的 YYYYMMDD 格式
            const dayList = [];
            for (let date = new Date(weekStartDate); date <= weekEndDate; date.setDate(date.getDate() + 1)) {
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const formattedDate = `${year}${month}${day}`;
                dayList.push(formattedDate);
            }
            console.log(dayList);
            this.setData({
                yearMonthWeek: yearMonthWeek,
                dayList: dayList,
                weekvalue:weekNumber
            }, () => {
                this.getdayXList();
                if (this.data.zhichushourutype == 1) {
                    this.setData({
                        chartData: {
                            categories: this.data.dayXList,
                            series: [
                                {
                                    name: '支出数据',
                                    data: []
                                }
                            ]
                        }, // 线性图数据
                    })
                } else {
                    this.setData({
                        chartData: {
                            categories: this.data.dayXList,
                            series: [
                                {
                                    name: '收入数据',
                                    data: []
                                }
                            ]
                        }, // 线性图数据
                    })
                }


            });

            console.log(yearMonthWeek);
            this.loadStatistics();
        }

    },
    // 月份表单改变
    bindMonthChange(e) {
        // 目前时间
        const now = new Date();
        const value = e.detail.value;
        console.log(now + '和' + value);
        // 解析用户选择的年月
        const [year, month] = value.split('-');

        // 创建一个代表用户选择的日期的 Date 对象
        const selectedDate = new Date(year, month - 1); // 月份从 0 开始
        if (selectedDate > now) {
            wx.showToast({
                title: '选择的日期大于当前日期!',
                icon: 'none'
            });
        } else {
            // 将月份转换为字符串，确保月份总是两位数
            const formattedMonth = month.padStart(2, '0');
            this.setData({
                year: year,
                month: formattedMonth
            });
            this.loadStatistics();
        }

    },
    // 年份时间改变
    bindYearChange(e) {
        // 目前时间
        const now = new Date();
        // 处理年份选择
        const Syear = new Date(e.detail.value);
        const year = new Date(e.detail.value).getFullYear();
        if (Syear > now) {
            wx.showToast({
                title: '选择的日期大于当前日期!',
                icon: 'none'
            });
        } else {
            this.setData({
                year: year
            });
            this.loadStatistics();
        }

    },
    // 更新表的数据
    loadStatistics() {
        // 根据选择的时间和支出收入类型加载统计数据
        // const { timetype, zhichushourutype, year, month, weekvalue } = this.data;
        // 发起网络请求或进行其他数据处理
        if (this.data.timetype == 1) {
            this.getWeekChartData();
        } else if (this.data.timetype == 2) {
            this.getMonthChartData()
        } else {
            this.getYearChartData()
        }


    },

    onItemClick(e) {
        // 处理账本选择器的项点击事件
        console.log('Selected item:', e.detail);
    },

    getWeeks(e) {
        // 处理周选择器的变化
        this.setData({
            weekvalue: e.detail.value
        });
        this.loadStatistics();
    }
});